import { _decorator, Component, Node, Button, EditBox, Label, EventHandler } from 'cc';
import { GameHelper } from './GameHelper';
import { WSSHelper } from './WSSHelper';
const { ccclass, property } = _decorator;

@ccclass('InitHelper')
export class InitHelper extends Component {

    @property(Button)
    startButton: Button;

    @property(Button)
    stopButton: Button;

    @property(EditBox)
    urlInput: EditBox;

    @property(Label)
    logLabel: Label;


    @property(Node)
    playerPanels: Node;
    wss: WSSHelper;

    wssUrl: string = "ws://game.adq.xin:8974/conn";
    gameHelper:GameHelper;
    start() {
        WSSHelper.logCallback = (str) => this.print(str);
        console.log("初始化数据！");
        var event = new EventHandler();
        event.handler = "startClick";
        event.target = this.node;
        event.component = "InitHelper";
        this.startButton.clickEvents.push(event)

        var event2 = new EventHandler();
        event2.handler = "stopClick";
        event2.target = this.node;
        event2.component = "InitHelper";
        this.stopButton.clickEvents.push(event2)
        this.gameHelper=new GameHelper(this.playerPanels);
        if (!this.wss) {
            this.wss = new WSSHelper();
            this.wss.start(this.wssUrl);
            this.wss.recvCallback = (data) => {
                this.gameHelper.coomand(data); 
            }
        }

    }
    print(str: string) {
        this.logLabel.string = str + "\n" + this.logLabel.string;
    }
    preUrl: string;
    startClick() {
        console.log("点击开始按钮！");
        if (!this.wss || !this.wss.isOpen) {
            this.print("socket 启动中!");
            return;
        }
        if (this.preUrl) {
            this.stopWebsocket();
        }
        var url = this.urlInput.string;
        this.preUrl = url;
        this.wss.enable(true, url);
    }
    stopClick() {
        console.log("点击关闭按钮！");
        if (!this.wss) {
            return;
        }
        this.stopWebsocket();
    }

    stopWebsocket() {
        this.gameHelper.clear();
        if (this.wss) {
            this.wss.enable(false, this.preUrl);
        }
    }
    recvDanDanMu(data: any) {

    }
    update(deltaTime: number) {

    }
}

